# -*- coding: utf-8 -*-
# @Time    : 2024/5/15 14:30
# @Author  : Jonny
# @File    : LuckDynamicConditionHelperUtils.py
# @Describe: 解析动态查询条件辅助类

import urllib.parse
import json


class LuckDynamicConditionHelperUtils(object):

    def parse_dynamic_condition(self, dynamic_condition):
        # URL解码
        dynamic_condition = urllib.parse.unquote(dynamic_condition)
        # 尝试将解码后的字符串解析为JSON
        try:
            json_data = json.loads(dynamic_condition)
            json_str = json_data["jsonStr"]
            json_conditions = json.loads(json_str)
            conditions = []
            for condition in json_conditions:
                field = condition['conditionFieldVal']
                datatype = condition['datatype']
                operator = condition['conditionOptionVal']
                value = condition['conditionValueVal']['value']

                # 这里需要将日期按照数据库类型进行转换
                if datatype == 'date':
                    field = f"date_format({field} , '%Y-%m-%d')"
                elif datatype == 'datetime':
                    field = f"date_format({field} , '%Y-%m-%d %H:%i:%s')"
                else:
                    pass

                # 根据操作符构建条件字符串
                if operator == 'equal':
                    condition_str = f"{field} = '{value}'"
                elif operator == 'unequal':
                    condition_str = f"{field} != '{value}'"
                elif operator == 'empty':
                    value = ''
                    condition_str = f"{field} == '{value}'"
                elif operator == 'notempty':
                    value = ''
                    condition_str = f"{field} != '{value}'"
                elif operator == 'like':
                    # 注意：这里使用了%作为通配符，但要根据实际情况调整
                    condition_str = f"{field} like '%{value}%'"
                elif operator == 'between':
                    value_left = condition['conditionValueLeftVal']['value']
                    value_right = condition['conditionValueRightVal']['value']
                    # 注意：这里使用了%作为通配符，但要根据实际情况调整
                    condition_str = f"{field} between '{value_left}' and '{value_right}'"
                else:
                    # 对于其他操作符，你可能需要添加额外的逻辑
                    condition_str = ""

                conditions.append(condition_str)

                # 使用'AND'连接多个条件
            if conditions:
                return ' AND (' + ' AND '.join(conditions) + ') '
            else:
                return ''

        except json.JSONDecodeError as e:
            print(f"无法解析JSON: {e}")
